using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows.Forms;
using ctsu.Admin.Forms;
using ctsu.Admin.Forms.CoreLab;
using ctsu.BaseForms;
using ctsu.Data;
using ctsu.Security;
using ctsu.Shared;

using Syncfusion.Windows.Forms.Grid;
using Syncfusion.Windows.Forms.Tools;

namespace ctsu.Admin.BusLogic.CoreLab
{
	public class BLFormSst : BLCoreLabFormBaseImpl
	{
		#region control references
		private TextBox _mrn;
		private TextBox _patientName;
		private TextBox _otherID;
		private TextBox _batchNum;

		private Button _btnProtocol;
		private Button _btnNewSample;
		private Button _btnAddBatch;
		private Button _btnEditBatch;
		private Button _btnClear;
		private Button _btnRemoveBatch;
		private Button _btnImport;

		private Button _btnPrint;

		protected TextBox _protocol;
		//protected TextBox _spid;
		private TextBox _protocolNumber;
		private TextBox _investigator;

		private DateTimePickerAdv _recDate;
		private DateTimePickerAdv _apptDate;
		private DateTimePickerAdv _outDate;

		private TextBox _labelsNum;
		private TextBox _specimensNumber;
		private TextBox _sampleVolume;

		//location
		private ComboBox _freezer;
		private NumericUpDown _shelf;
		private NumericUpDown _rack;
		private NumericUpDown _box;

		private TextBox _disposition;
		private TextBox _notes;

		private ComboBox _sampleType;
		private CheckBox _chkKeepSame;
		#endregion

		public BLFormSst(FormMain formMain, FormBase form, FormInfoBase formInfo, DataTable tableSchema, Permission formSecurity, Hashtable configData)
			: base(formMain, form, formInfo, tableSchema, formSecurity, configData)
		{

		}

		#region initialize
		protected override void _vcManager_OnAfterHookEvents()
		{
			_batchNum = (TextBox)Forms.Utils.GetControlByName("ID", this._form.Controls);
			_otherID = (TextBox)Forms.Utils.GetControlByName("OtherID", this._form.Controls);
			_mrn = (TextBox)Forms.Utils.GetControlByName("MRN", this._form.Controls);
			_patientName = (TextBox)Forms.Utils.GetControlByName("PatientName", this._form.Controls);

			_btnProtocol = (Button)Forms.Utils.GetControlByName("btnProtocol", this._form.Controls);
			_btnNewSample = (Button)Forms.Utils.GetControlByName("btnNewSample", this._form.Controls);
			_btnAddBatch = (Button)Forms.Utils.GetControlByName("btnAddBatch", this._form.Controls);
			_btnEditBatch = (Button)Forms.Utils.GetControlByName("btnEditBatch", this._form.Controls);
			_btnClear = (Button)Forms.Utils.GetControlByName("btnClear", this._form.Controls);
			_btnRemoveBatch = (Button)Forms.Utils.GetControlByName("btnRemoveBatch", this._form.Controls);
			_btnImport = (Button)Forms.Utils.GetControlByName("btnImport", this._form.Controls);
			_btnPrint = (Button)Forms.Utils.GetControlByName("btnPrint", this._form.Controls);
			_chkPrintReport = (CheckBox)Forms.Utils.GetControlByName("chkPrintReport", this._form.Controls);
			_chkPrintSelected = (CheckBox)Forms.Utils.GetControlByName("chkPrintSelected", this._form.Controls);

			_protocol = (TextBox)Forms.Utils.GetControlByName("Protocol", this._form.Controls);
			//_spid = (TextBox)Forms.Utils.GetControlByName("SPID", this._form.Controls);
			_protocolNumber = (TextBox)Forms.Utils.GetControlByName("ProtocolNumber", this._form.Controls);
			_investigator = (TextBox)Forms.Utils.GetControlByName("Investigator", this._form.Controls);

			_recDate = (DateTimePickerAdv)Forms.Utils.GetControlByName("RecDate", this._form.Controls);
			_apptDate = (DateTimePickerAdv)Forms.Utils.GetControlByName("ApptDate", this._form.Controls);
			_outDate = (DateTimePickerAdv)Forms.Utils.GetControlByName("OutDate", this._form.Controls);
			_labelsNum = (TextBox)Forms.Utils.GetControlByName("LabelsNum", this._form.Controls);

			_specimensNumber = (TextBox)Forms.Utils.GetControlByName("SpecimensNumber", this._form.Controls);
			_sampleVolume = (TextBox)Forms.Utils.GetControlByName("SampleVolume", this._form.Controls);

			//_location = (TextBox)Forms.Utils.GetControlByName("Location", this._form.Controls);
			_freezer = (ComboBox)Forms.Utils.GetControlByName("Freezer", this._form.Controls);
			_shelf = (NumericUpDown)Forms.Utils.GetControlByName("Shelf", this._form.Controls);
			_rack = (NumericUpDown)Forms.Utils.GetControlByName("Rack", this._form.Controls);
			_box = (NumericUpDown)Forms.Utils.GetControlByName("Box", this._form.Controls);


			_disposition = (TextBox)Forms.Utils.GetControlByName("Disposition", this._form.Controls);
			_notes = (TextBox)Forms.Utils.GetControlByName("Notes", this._form.Controls);

			_chkKeepSame = (CheckBox)Forms.Utils.GetControlByName("chkKeepSame", this._form.Controls);
			_sampleType = (ComboBox)Forms.Utils.GetControlByName("SampleType", this._form.Controls);
		}

		protected override void SetControlsEnabled(bool enable)
		{
			base.SetControlsEnabled(enable);

			_btnProtocol.Enabled = enable;
			_btnNewSample.Enabled = enable;
			_btnAddBatch.Enabled = enable; ;
			_btnClear.Enabled = enable;
			_btnImport.Enabled = enable;

			if (enable == false)
			{
				_btnEditBatch.Enabled = enable;
				_btnRemoveBatch.Enabled = enable;
			}

			_otherID.Enabled = enable;
			_otherID.Text = "";
			_mrn.Enabled = enable;
			_mrn.Text = "";
			_patientName.Enabled = enable;
			_patientName.Text = "";

			_protocol.Enabled = enable;
			_protocol.Text = "";
			//_spid.Enabled = enable;
			//_spid.Text = "";
			_protocolNumber.Enabled = enable;
			_protocolNumber.Text = "";
			_investigator.Enabled = enable;
			_investigator.Text = "";

			_recDate.Enabled = enable;
			_recDate.Value = DateTime.Today;
			_recDate.IsNullDate = true;
			_apptDate.Enabled = enable;
			_apptDate.Value = DateTime.Today;
			_apptDate.IsNullDate = true;
			_outDate.Enabled = enable;
			_outDate.Value = DateTime.Today;
			_outDate.IsNullDate = true;

			_labelsNum.Enabled = enable;
			_labelsNum.Text = "1";

			_specimensNumber.Enabled = enable;
			_specimensNumber.Text = "1";
			_sampleVolume.Enabled = enable;
			_sampleVolume.Text = "";

			_freezer.Enabled = enable;
			_freezer.SelectedIndex = -1;
			_freezer.SelectedIndex = -1;
			_shelf.Enabled = enable;
			_shelf.Value = 0;
			_rack.Enabled = enable;
			_rack.Value = 0;
			_box.Enabled = enable;
			_box.Value = 0;

			_disposition.Enabled = enable;
			_disposition.Text = "";
			_notes.Enabled = enable;
			_notes.Text = "";

			_chkKeepSame.Enabled = enable;
			_chkKeepSame.Checked = true;
			_sampleType.SelectedIndex = -1;
			_sampleType.SelectedIndex = -1;
			_sampleType.Enabled = enable;
		}

		public override void InitializeEmptyControls()
		{
			base.InitializeEmptyControls();
			_sampleType.SelectedIndex = -1;
			_sampleType.SelectedIndex = -1;
			_freezer.SelectedIndex = -1;
			_freezer.SelectedIndex = -1;
		}
		#endregion initialize

		#region search
		public override void Search(object sender)
		{
			Control ctl = (Control)sender;
			ctl.Enabled = false;

			SearchSamples spd = new SearchSamples();
			spd.ShowDialog(this._form);
			if (spd.SearchChoice == 0)
				base.Search(sender);
			else if (spd.SearchChoice == 1)
				SelectByLabel();

			ctl.Enabled = true;
		}

		private void SelectByLabel()
		{

			Cursor.Current = Cursors.WaitCursor;

			SearchInfo si = (SearchInfo)this.FormInfo.SearchFormInfo["Sst"];
			if (si == null)
			{
				MessageBox.Show("Search criteria is not defined.", "Search Criteria Not Fount",
					MessageBoxButtons.OK, MessageBoxIcon.Stop);
				return;
			}

			FormSearch fs = new FormSearch();
			//set the title bar
			//fs.Text = si.Name + " Search";

			//get the search fields			
			foreach (ReportColumn rc in si.SearchFields)
				fs.SearchFields.Items.Add(rc);

			//design list view for result fields			
			ListView lvw = fs.SearchResults;
			lvw.Columns.Clear();
			if (lvw != null)
			{
				foreach (ReportColumn rc in si.SearchResultCols)
				{
					ColumnHeader ch = new ColumnHeader();
					ch.Text = rc.DisplayName;
					ch.Width = -2;
					lvw.Columns.Add(ch);
				}
			}

			SearchSamplesController sc = new SearchSamplesController(fs, si);
			fs.Controller = sc;
			fs.Owner = this._form;
			sc.ItemSelected += new BaseForms.BusinessLogicEvents.BLSelectedItemEventHandler(sc_ItemSelected);
			fs.Closing += new CancelEventHandler(fs_Closing);
			IsSearchVisible = true;
			fs.Show();
		}

		private void sc_ItemSelected(object sender, BLReturnIDEventArgs e)
		{
			if (e.ID > 0)
			{
				Console.WriteLine("Selected ID: " + e.ID.ToString());
				if (GetData(e.ID))
				{
					if (this.FormMode == EditMode.Load)
						SetFormMode(EditMode.Read);
				}
			}
		}

		private void fs_Closing(object sender, CancelEventArgs e)
		{
			IsSearchVisible = false;
			this._form.btnSearch.Enabled = true;
		}
		#endregion search

		public override void GenericClick(Control sender)
		{
			if (sender.Name == "btnImport")
				ImportSamples();
			if (sender.Name == "btnProtocol")
				SelectProtocol();
			if (sender.Name == "btnAddBatch")
				AddToBatch();
			if (sender.Name == "btnEditBatch")
				EditBatch();
			if (sender.Name == "btnRemoveBatch")
				RemoveBatch();
			if (sender.Name == "btnNewSample")
				NewSample();
			if (sender.Name == "btnClear")
				ClearInfo();
			if (sender.Name == "btnPrint")
				DoPrint();
		}

		#region import
		private void ImportSamples()
		{
			SampleChooser2Dlg dlc = new SampleChooser2Dlg();
			dlc.Owner = this._form;
			dlc.Text = "Import Samples";
			dlc.SelectSampleClick += new ctsu.Admin.Forms.CoreLab.SampleChooser2Dlg.SelectSampleButtonClickEventHandler(dlc_SelectSampleClick);
			dlc.Show();
		}

		private void dlc_SelectSampleClick(object sender, SelectSamplesEventArgs e)
		{
			if (e.SelectType == 0)
				RetrieveSampleBatch(e.ID, 0);
			else if (e.SelectType == 1)
				RetrieveOneSample(e.ID, true);
			else
				RetrieveSampleBatch(e.ID, 1);

			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)_gridBLs["SstItems"];
			GridControl grid = fgbl.Grid;
			if (grid.RowCount > 0)
			{
				if (!this._btnEditBatch.Enabled)
				{
					this._btnEditBatch.Enabled = true;
					this._btnRemoveBatch.Enabled = true;
					this._form.btnSave.Enabled = true;
				}
			}
		}

		private void RetrieveSampleBatch(int id, int type)
		{
			StringBuilder sb = new StringBuilder();
			string batch = "BatchInNum";
			if (type == 1)
				batch = "BatchOutNum";

			string sql = "SELECT t.ID, t.TestType, d.Protocol, p.MRN, p.OtherPatientID, " +
				"p.LastName + N'.' + p.FirstName AS PatientName, d.SampleType, d.VisitDate " +
				"FROM TestSamples t INNER JOIN DrawSamples d ON t.DrawSample = d.ID INNER JOIN " +
				"Patient p ON d.Patient = p.ID " +
				" WHERE t." + batch + " =" + id +
				" ORDER BY t.ID";

			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)_gridBLs["SstItems"];
			GridControl grid = fgbl.Grid;

			//SqlConnection conn = LoginForm.GetSqlConnection();			
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql);

				Sample samp = null;
				string message = "";

				grid.BeginUpdate();
				while (reader.Read())
				{
					Cursor.Current = Cursors.WaitCursor;

					samp = new Sample();
					samp.TestID = reader.GetInt32(0);
					if (IsInList(samp.TestID))
						continue;
					samp.TestType = reader.GetInt32(1);
					samp.Protocol = reader.GetInt32(2);
					//get protocolInfo
					samp.ProtocolInfo = CoreLabUtils.GetProtocolInfo(samp.Protocol, out message);
					if (!reader.IsDBNull(3))
						samp.MRN = reader.GetString(3);
					if (!reader.IsDBNull(4))
						samp.OtherID = reader.GetString(4);
					if (!reader.IsDBNull(5))
						samp.PatientName = reader.GetString(5);

					samp.SampleType = reader.GetInt32(6);
					samp.VisitDate = reader.GetDateTime(7);
					//samp.PatientID = reader.GetInt32(3);
					////get the patient info
					//samp.PatientInfo = CoreLabUtils.GetPatientInfo(samp.PatientID, out message);
					fgbl.AddRow(samp, 0);
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve sample!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Get Sample Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				grid.EndUpdate();
			}

		}

		private void RetrieveOneSample(int id, bool displayMessage)
		{
			StringBuilder sb = new StringBuilder();

			if (IsInList(id))
			{
				if (displayMessage)
				{
					sb.Append("Sample ID: " + id + " is already in the list");
					MessageBox.Show(this._form, sb.ToString(), "Duplicate ID",
						MessageBoxButtons.OK, MessageBoxIcon.Information);
				}
				return;
			}

			string sql = "SELECT t.ID, t.TestType, d.Protocol, p.MRN, p.OtherPatientID, " +
				"p.LastName + N'.' + p.FirstName AS PatientName, d.SampleType, d.VisitDate " +
				"FROM TestSamples t INNER JOIN DrawSamples d ON t.DrawSample = d.ID INNER JOIN " +
				"Patient p ON d.Patient = p.ID " +
				" WHERE t.ID =" + id +
				" ORDER BY t.ID";

			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)_gridBLs["SstItems"];
			GridControl grid = fgbl.Grid;

			//SqlConnection conn = LoginForm.GetSqlConnection();			
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql);

				Sample samp = null;
				string message = "";

				grid.BeginUpdate();
				if (reader.Read())
				{
					Cursor.Current = Cursors.WaitCursor;

					samp = new Sample();
					samp.TestID = reader.GetInt32(0);
					samp.TestType = reader.GetInt32(1);
					samp.Protocol = reader.GetInt32(2);
					//get protocolInfo
					samp.ProtocolInfo = CoreLabUtils.GetProtocolInfo(samp.Protocol, out message);
					if (!reader.IsDBNull(3))
						samp.MRN = reader.GetString(3);
					if (!reader.IsDBNull(4))
						samp.OtherID = reader.GetString(4);
					if (!reader.IsDBNull(5))
						samp.PatientName = reader.GetString(5);

					samp.SampleType = reader.GetInt32(6);
					samp.VisitDate = reader.GetDateTime(7);
					//samp.PatientID = reader.GetInt32(3);
					////get the patient info
					//samp.PatientInfo = CoreLabUtils.GetPatientInfo(samp.PatientID, out message);
					fgbl.AddRow(samp, 0);
				}
				else
				{
					sb.Append("Sample ID: " + id + " could not be found");
					MessageBox.Show(this._form, sb.ToString(), "Sample Not Found",
						MessageBoxButtons.OK, MessageBoxIcon.Information);
					reader.Close();
					return;
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve sample!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Get Sample Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				grid.EndUpdate();
			}
		}

		private bool IsInList(int id)
		{
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("SstItems", this._form.Controls);
			GridStyleInfo gsi = null;

			if (grid.RowCount == 0)
				return false;

			for (int i = 1; i <= grid.RowCount; i++)
			{
				gsi = grid[i, 2];
				if (gsi.Text.Length > 0)
					if (Convert.ToInt32(gsi.CellValue) == id)
						return true;
			}
			return false;
		}
		#endregion import

		private void DoPrint()
		{
			string url = Properties.Settings.Default.Crema2_ReportingServices_ReportingService.ToString().Trim();
			string server = GetServerFromUrl(url);
			StringBuilder sb = new StringBuilder("http://" + server + "/reportserver?");
			sb.Append("%2fGCRC%2fCore+Lab%2fSst+Batch+Detail&rs:Command=Render&BatchNum=" + this._batchNum.Text);

			System.Diagnostics.Process.Start(sb.ToString());
		}

		private string GetServerFromUrl(string url)
		{
			int pos1 = url.IndexOf("//");
			int pos2 = url.IndexOf("/", pos1 + 2);

			string retVal = url.Substring(pos1 + 2, (pos2 - pos1) - 2);
			return retVal;
		}

		#region get display data
		public override void DisplayData()
		{
			base.DisplayData();
			if (this._batchNum.Text.Length > 0)
				this._btnPrint.Enabled = true;
			else
				this._btnPrint.Enabled = false;

		}

		private void ClearInfo()
		{
			ClearLocation();
			_protocol.Text = "";
			_protocol.Tag = null;
			//_spid.Text = "";
			_protocolNumber.Text = "";
			_investigator.Text = "";

			_recDate.Value = DateTime.Today;
			_recDate.IsNullDate = true;
			_apptDate.Value = DateTime.Today;
			_apptDate.IsNullDate = true;
			_outDate.Value = DateTime.Today;
			_outDate.IsNullDate = true;

			_otherID.Text = "";
			_mrn.Text = "";
			_patientName.Text = "";

			_specimensNumber.Text = "1";
			_labelsNum.Text = "1";
			_sampleVolume.Text = "";

			_disposition.Text = "";
			_notes.Text = "";

			_sampleType.SelectedIndex = -1;
			_sampleType.SelectedIndex = -1;
		}

		private void ClearLocation()
		{
			this._freezer.SelectedIndex = -1;
			this._freezer.SelectedIndex = -1;
			this._shelf.Value = 0;
			this._rack.Value = 0;
			this._box.Value = 0;

		}

		private void DisplayLocationInControls(string location)
		{
			if (location.Length == 0)
			{
				ClearLocation();
				return;
			}

			string[] a = location.Split(',');
			foreach (string s in a)
			{
				if (s.StartsWith("Fz"))
				{
					this._freezer.SelectedValue = Convert.ToInt32(s.Substring(3));
				}
				if (s.StartsWith("Sf"))
				{
					this._shelf.Value = Convert.ToInt32(s.Substring(3));
				}
				if (s.StartsWith("Rk"))
				{
					this._rack.Value = Convert.ToInt32(s.Substring(3));
				}
				if (s.StartsWith("Bx"))
				{
					this._box.Value = Convert.ToInt32(s.Substring(3));
				}
			}
		}

		protected override void grd_CellDoubleClick(object sender, GridCellClickEventArgs e)
		{
			if (e.RowIndex < 1)
				return;
			if (this.FormMode == EditMode.Edit || this.FormMode == EditMode.New)
				FillControlsWithRowData(e.RowIndex);
		}

		private void FillControlsWithRowData(int row)
		{
			GridControl grid = ((BLCoreLabFormGridBaseImpl)this._gridBLs["SstItems"]).Grid;

			ProtocolInfo pri = new ProtocolInfo();
			ProtocolInfo pri2 = (ProtocolInfo)grid[row, 3].Tag;
			pri.ID = pri2.ID;
			//pri.SPID = pri2.SPID;
			pri.Number = pri2.Number;
			pri.Investigator = pri2.Investigator;
			SetProtocolData(pri);

			if (grid[row, 4].Text.Length == 0)
				this._recDate.IsNullDate = true;
			else
				this._recDate.Value = DateTime.Parse(grid[row, 4].Text);

			if (grid[row, 5].Text.Length == 0)
				this._apptDate.IsNullDate = true;
			else
				this._apptDate.Value = DateTime.Parse(grid[row, 5].Text);

			if (grid[row, 6].Text.Length == 0)
				this._outDate.IsNullDate = true;
			else
				this._outDate.Value = DateTime.Parse(grid[row, 6].Text);

			this._mrn.Text = grid[row, 7].Text;
			this._otherID.Text = grid[row, 8].Text;
			this._patientName.Text = grid[row, 9].Text;
			this._sampleType.Text = grid[row, 10].FormattedText;
			this._specimensNumber.Text = grid[row, 12].Text;
			this._sampleVolume.Text = grid[row, 13].Text;

			string sVal = grid[row, 14].Text;
			DisplayLocationInControls(sVal);

			this._disposition.Text = grid[row, 15].Text;
			this._notes.Text = grid[row, 16].Text;
		}
		#endregion get display data

		#region select patient and protocol
		private void SelectProtocol()
		{
			SelectProtocolDlg spd = new SelectProtocolDlg();
			spd.radioButton3.Visible = false;
			spd.ShowDialog(this._form);
			if (spd.SearchChoice == 0)
				SelectProtocolStandard();
			else if (spd.SearchChoice == 1)
				SelectProtocolByInvestigator();
		}

		private void SelectProtocolByInvestigator()
		{
			StringBuilder sb = new StringBuilder();
			Cursor.Current = Cursors.WaitCursor;

			SearchInfo si = (SearchInfo)this._formInfo.SearchFormInfo["Investigator"];

			try
			{
				FormSearchBase fs = (FormSearchBase)SearchUtils.GetSearchDialog(si);
				fs.ShowDialog(this._form);
				if (fs.DialogResult == DialogResult.OK)
				{
					int id = fs.SelectedID;
					GetProtocolData(id);
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not display protocol seach dialog!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Display Search Dialog Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void SelectProtocolStandard()
		{
			StringBuilder sb = new StringBuilder();
			Cursor.Current = Cursors.WaitCursor;

			SearchInfo si = (SearchInfo)this._formInfo.SearchFormInfo["Protocol"];

			try
			{
				FormSearchBase fs = (FormSearchBase)SearchUtils.GetSearchDialog(si);
				fs.ShowDialog(this._form);
				if (fs.DialogResult == DialogResult.OK)
				{
					Console.WriteLine("DialogResult.OK");
					int id = fs.SelectedID;
					GetProtocolData(id);
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not display protocol seach dialog!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Display Search Dialog Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void GetProtocolData(int id)
		{
			string message = "";
			ProtocolInfo pi = CoreLabUtils.GetProtocolInfo(id, out message);
			SetProtocolData(pi);
		}
		private void SetProtocolData(ProtocolInfo pi)
		{
			this._protocol.Text = pi.ID.ToString();
			this._protocol.Tag = pi;
			this._form.tip.SetToolTip(this._protocol, pi.GetToolTip());
			//this._spid.Text = pi.SPID.ToString();
			this._protocolNumber.Text = pi.Number;
			this._investigator.Text = pi.Investigator;
		}
		#endregion select patient and protocol

		#region add to batch
		private void AddToBatch()
		{
			if (VerifyAddToBatch())
			{
				IBLCoreLabFormGridBase fgbl = (IBLCoreLabFormGridBase)this._gridBLs["SstItems"];
				int numLabels = Convert.ToInt32(_labelsNum.Text);

				Sample samp = null;
				for (int i = 0; i < numLabels; i++)
				{
					samp = new Sample();
					samp.Protocol = Convert.ToInt32(_protocol.Text);
					samp.ProtocolInfo = (ProtocolInfo)_protocol.Tag;
					samp.ReceiveDate = this._recDate.Value;
					if (!this._apptDate.IsNullDate)
						samp.VisitDate = this._apptDate.Value;
					if (!this._outDate.IsNullDate)
						samp.OutDate = this._outDate.Value;

					samp.MRN = this._mrn.Text;
					samp.OtherID = this._otherID.Text;
					samp.PatientName = this._patientName.Text;
					samp.SampleType = (int)_sampleType.SelectedValue;
					samp.SpecimenNumber = int.Parse(this._specimensNumber.Text);
					samp.SampleVolume = this._sampleVolume.Text;
					samp.Location = GetFormatatedLocation();
					samp.Disposition = this._disposition.Text;
					samp.SmallNote = _notes.Text;
					fgbl.AddRow(samp, 0);
				}
			}
			if (!_chkKeepSame.Checked)
				ClearInfo();
		}

		private string GetFormatatedLocation()
		{
			if (_freezer.SelectedIndex == -1)
				return "";

			string location = "Fz:" + this._freezer.SelectedValue.ToString() + "," +
				"Sf:" + this._shelf.Value.ToString() + "," +
				"Rk:" + this._rack.Value.ToString() + "," +
				"Bx:" + this._box.Value.ToString();
			return location;
		}


		private bool VerifyAddToBatch()
		{
			StringBuilder sb = new StringBuilder();
			if (_labelsNum.Enabled && _labelsNum.Text.Length == 0)
			{
				sb.Append("You must enter the number of items!");
				MessageBox.Show(this._form, sb.ToString(), "Required Field", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				_labelsNum.Focus();
				return false;
			}

			if (_protocol.Text.Length == 0)
			{
				sb.Append("You must enter the protocol!");
				MessageBox.Show(this._form, sb.ToString(), "Required Field", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				_protocol.Focus();
				return false;
			}

			if (_recDate.IsNullDate)
			{
				sb.Append("You must enter the received date!");
				MessageBox.Show(this._form, sb.ToString(), "Required Field", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				_recDate.Focus();
				return false;
			}

			if (_sampleType.SelectedIndex == -1)
			{
				sb.Append("You must enter the sample type!");
				MessageBox.Show(this._form, sb.ToString(), "Required Field", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				_sampleType.Focus();
				return false;
			}
			try
			{
				int i = int.Parse(this._specimensNumber.Text);
			}
			catch
			{
				sb.Append("You must enter a number for the specimen number field!");
				MessageBox.Show(this._form, sb.ToString(), "Required Field", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				_specimensNumber.Focus();
				return false;
			}
			return true;

		}
		#endregion add to batch

		#region edit batch
		private void RemoveBatch()
		{
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("SstItems", this._form.Controls);

			GridRangeInfoList list;
			list = grid.Selections.GetSelectedRows(true, false);
			if (list.Count == 0)
				return;

			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)this._gridBLs["SstItems"];

			ArrayList alRows = new ArrayList();
			int row = 0;
			int top = 0;
			int bottom = 0;
			for (int i = 0; i < list.Count; i++)
			{
				top = list[i].Top;
				bottom = list[i].Bottom;
				if (bottom > top)
					GetSelectedRows(alRows, top, bottom);
				else
					alRows.Add(list[i].Top);
			}
			for (int i = 0; i < alRows.Count; i++)
			{
				row = (int)alRows[i];
				row -= i;
				DataRow dr = (DataRow)fgbl.Grid[row, 0].Tag;
				dr.RejectChanges();
				fgbl.RemoveRow(row);
			}
			this._form.btnSave.Enabled = true;
		}

		private void GetSelectedRows(ArrayList alRows, int top, int bottom)
		{
			int rows = bottom - top + 1;
			for (int i = 0; i < rows; i++)
				alRows.Add(top + i);
		}

		private void EditBatch()
		{
			this._btnEditBatch.Enabled = false;
			SstEditDlg ebd = new SstEditDlg();
			//			if(!ebd.Initialize())
			//				return;
			ebd.ButtonClick += new ctsu.Admin.Forms.CoreLab.SstEditDlg.ButtonClickEventHandler(ebd_ButtonClick);
			ebd.Closing += new CancelEventHandler(ebd_Closing);
			ebd.Owner = this._form;
			ebd.Show();
			//ebd.ClearControls();
		}

		private void ebd_ButtonClick(object sender, EditBatchEventArgs e)
		{
			if (e.ButtonName == "ReplaceSelected")
				EditReplaceSelected(e.ReplaceColumns, e.ColumnMatch);
			if (e.ButtonName == "ReplaceAll")
				EditReplaceAll(e.ReplaceColumns, e.ColumnMatch);
		}

		private void ebd_Closing(object sender, CancelEventArgs e)
		{
			SstEditDlg ebd = (SstEditDlg)sender;
			ebd.ButtonClick -= new SstEditDlg.ButtonClickEventHandler(ebd_ButtonClick);
			ebd.Closing -= new CancelEventHandler(ebd_Closing);
			if (this._formMode == EditMode.Edit || this._formMode == EditMode.New)
				this._btnEditBatch.Enabled = true;
		}

		private void EditReplaceAll(bool[] replaceColumns, Hashtable columnMatch)
		{
			Sample samp = new Sample();
			if (!SetReplacementColumns(replaceColumns, ref samp))
				return;

			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)this._gridBLs["SstItems"];

			for (int i = 1; i <= fgbl.Grid.RowCount; i++)
				fgbl.ReplaceRow(samp, i);
			this._form.btnSave.Enabled = true;
		}

		private void EditReplaceSelected(bool[] replaceColumns, Hashtable columnMatch)
		{
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("SstItems", this._form.Controls);

			GridRangeInfoList list;
			list = grid.Selections.GetSelectedRows(true, false);

			Sample samp = new Sample();
			if (!SetReplacementColumns(replaceColumns, ref samp))
				return;

			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)this._gridBLs["SstItems"];

			foreach (GridRangeInfo range in list)
			{
				for (int i = range.Top; i <= range.Bottom; i++)
				{
					fgbl.ReplaceRow(samp, i);
					this._form.btnSave.Enabled = true;
				}
			}
		}

		private bool SetReplacementColumns(bool[] replaceColumns, ref Sample samp)
		{
			//initialize some of the members
			samp.SampleType = -1;
			samp.SpecimenNumber = -1;

			StringBuilder sb = new StringBuilder();
			if (replaceColumns[0])
			{
				if (!VerifyAddToBatch())
					return false;
				samp.Protocol = Convert.ToInt32(_protocol.Text);
				samp.ProtocolInfo = (ProtocolInfo)_protocol.Tag;
				samp.ReceiveDate = this._recDate.Value;
				if (!this._apptDate.IsNullDate)
					samp.VisitDate = this._apptDate.Value;
				if (!this._outDate.IsNullDate)
					samp.OutDate = this._outDate.Value;

				samp.MRN = this._mrn.Text;
				samp.OtherID = this._otherID.Text;
				samp.PatientName = this._patientName.Text;
				samp.SampleType = (int)_sampleType.SelectedValue;
				samp.SpecimenNumber = int.Parse(this._specimensNumber.Text);
				samp.SampleVolume = this._sampleVolume.Text;
				samp.Location = GetFormatatedLocation();
				samp.Disposition = this._disposition.Text;
				samp.SmallNote = _notes.Text;
			}
			if (replaceColumns[1])
			{
				if (_protocol.Text.Length == 0)
				{
					sb.Append("You must enter the protocol!");
					MessageBox.Show(this._form, sb.ToString(), "Protocol", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					_protocol.Focus();
					return false;
				}
				samp.Protocol = Convert.ToInt32(_protocol.Text);
				samp.ProtocolInfo = (ProtocolInfo)_protocol.Tag;
			}

			if (replaceColumns[2])
			{
				if (_recDate.IsNullDate)
				{
					sb.Append("You must enter the received date!");
					MessageBox.Show(this._form, sb.ToString(), "Received Date", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					_recDate.Focus();
					return false;
				}
				samp.ReceiveDate = this._recDate.Value;
			}

			if (replaceColumns[3])
			{
				if (_apptDate.IsNullDate)
				{
					sb.Append("You must enter the appointment date!");
					MessageBox.Show(this._form, sb.ToString(), "Appointment Date", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					_apptDate.Focus();
					return false;
				}
				samp.VisitDate = _apptDate.Value;
			}

			if (replaceColumns[4])
			{
				if (_outDate.IsNullDate)
				{
					sb.Append("You must enter the out date!");
					MessageBox.Show(this._form, sb.ToString(), "Out Date", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					_outDate.Focus();
					return false;
				}
				samp.OutDate = _outDate.Value;
			}

			if (replaceColumns[5])
			{
				if (_mrn.Text.Length == 0)
				{
					sb.Append("You must enter the MRN!");
					MessageBox.Show(this._form, sb.ToString(), "MRN", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					_mrn.Focus();
					return false;
				}
				samp.MRN = _mrn.Text;
			}

			if (replaceColumns[6])
			{
				if (_otherID.Text.Length == 0)
				{
					sb.Append("You must enter the Other ID!");
					MessageBox.Show(this._form, sb.ToString(), "Other ID", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					_otherID.Focus();
					return false;
				}
				samp.OtherID = _otherID.Text;
			}

			if (replaceColumns[7])
			{
				if (_patientName.Text.Length == 0)
				{
					sb.Append("You must enter the patient name!");
					MessageBox.Show(this._form, sb.ToString(), "Patient Name", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					_patientName.Focus();
					return false;
				}
				samp.PatientName = _patientName.Text;
			}

			if (replaceColumns[8])
			{
				if (_sampleType.SelectedIndex == -1)
				{
					sb.Append("You must enter the sample type!");
					MessageBox.Show(this._form, sb.ToString(), "Sample Type", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					_sampleType.Focus();
					return false;
				}
				samp.SampleType = (int)_sampleType.SelectedValue;
			}

			if (replaceColumns[9])
			{
				if (_specimensNumber.Text.Length == 0)
				{
					sb.Append("You must enter a number for the number of specimens!");
					MessageBox.Show(this._form, sb.ToString(), "Number of Specimens", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					_specimensNumber.Focus();
					return false;
				}
				try
				{
					samp.SpecimenNumber = int.Parse(_specimensNumber.Text);
				}
				catch
				{
					sb.Append("You must enter a number for the number of specimens!");
					MessageBox.Show(this._form, sb.ToString(), "Number of Specimens", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					_specimensNumber.Focus();
					return false;
				}
			}

			if (replaceColumns[10])
			{
				if (_sampleVolume.Text.Length == 0)
				{
					sb.Append("You must enter the sample volume!");
					MessageBox.Show(this._form, sb.ToString(), "Sample Volume", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					_sampleVolume.Focus();
					return false;
				}
				samp.SampleVolume = _sampleVolume.Text;
			}

			if (replaceColumns[11])
			{
				samp.Location = GetFormatatedLocation();
			}

			if (replaceColumns[12])
			{
				if (_disposition.Text.Length == 0)
				{
					sb.Append("You must enter the disposition!");
					MessageBox.Show(this._form, sb.ToString(), "Disposition", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					_disposition.Focus();
					return false;
				}
				samp.Disposition = _disposition.Text;
			}

			if (replaceColumns[13])
			{
				if (_notes.Text.Length == 0)
				{
					sb.Append("You must enter the notes!");
					MessageBox.Show(this._form, sb.ToString(), "Notes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					_notes.Focus();
					return false;
				}
				samp.SmallNote = _notes.Text;
			}

			return true;
		}
		#endregion edit batch

		#region new combo items
		private void NewSample()
		{
			StringBuilder sb = new StringBuilder();

			string sql = "SELECT Display " +
				" FROM SampleType_L " +
				" WHERE 1=2";

			DataTable tableSchema;
			try
			{
				tableSchema = Forms.Utils.GetTableSchema(null, sql);
				NewListRecordDlg nd = new NewListRecordDlg("Display", "SampleType_L", tableSchema);
				nd.ShowDialog(this._form);

				Forms.Utils.LoadCbo(_sampleType, "SampleType_L", true);
				_sampleType.SelectedValue = nd.NewID;

				//reset the grid column comboBox
				BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)_gridBLs["SstItems"];
				GridControl grid = fgbl.Grid;

				GridStyleInfo gsi = grid.ColStyles[9];
				SpecialLookup sl = (SpecialLookup)this._formInfo.SpecialLookups["SampleType"];
				Forms.Utils.LoadCbo(sl, gsi);
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Error encountered while retrieving table schema for SampleType.");
				sb.Append(Environment.NewLine);
				sb.Append("Error: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
		}
		#endregion new
	}
}
